package com.example.rabbitmqdemo.listeners;

import com.rabbitmq.client.Channel;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareBatchMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author wuyunbin
 */
@RabbitListener(queues = "simple")
@Component
public class SimpleListener {
    @RabbitHandler
    public SimpleMessageListenerContainer simpleHandler(ConnectionFactory connectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("simple");
        container.setMessageListener(new ChannelAwareBatchMessageListener() {

            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                try{
                    System.out.println(message.getBody());
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }catch (Exception e){
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                }
            }

            @Override
            public void onMessageBatch(List<Message> list, Channel channel) {

            }


        });

        return container;
    }
}
